package cn.edu.zafu.bigdata.yh;
import java.io.*;
import java.net.*;

public class UdpTimeServer {
    public static void main(String[] args) {
        int port = 6666; // 服务端端口号
        try {
            // 创建一个DatagramSocket，绑定端口号
            DatagramSocket serverSocket = new DatagramSocket(port);
            System.out.println("UDP Time Server is running on port " + port);

            // 持续监听客户端请求
            while (true) {
                // 创建一个字节数组用于接收数据
                byte[] receiveData = new byte[1024];
                // 创建一个DatagramPacket用于接收客户端请求
                DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);

                // 接收客户端请求
                serverSocket.receive(receivePacket);

                // 获取客户端的IP地址和端口号
                InetAddress clientAddress = receivePacket.getAddress();
                int clientPort = receivePacket.getPort();

                // 获取当前时间
                String currentTime = new java.util.Date(System.currentTimeMillis()).toString();

                // 发送时间给客户端
                byte[] sendData = currentTime.getBytes();
                DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, clientAddress, clientPort);
                serverSocket.send(sendPacket);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
